package com.htbb.test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public enum ThreadPool {
	Test {
		@Override
		protected ExecutorService init() {
			return Executors.newFixedThreadPool(10);
		}
	},
	NoLimit {
		@Override
		protected ExecutorService init() {
			return Executors.newCachedThreadPool();
		}
	},;

	public volatile ExecutorService pool;
	private static final Set<ExecutorService> pools = new HashSet<>();
	static {
		ThreadPool[] values = ThreadPool.values();
		for (ThreadPool threadPools : values) {
			threadPools.pool = threadPools.init();
			pools.add(threadPools.pool);
		}
	}

	private ThreadPool() {
	}

	public void setPool(ExecutorService pool) {
		this.pool = pool;
	}

	protected abstract ExecutorService init();

	public void execute(Runnable task) {
		if (pool != null) {
			pool.execute(task);
		}
	}

	public Future<?> submit(Callable<?> task) {
		if (pool != null) {
			return pool.submit(task);
		}
		return null;
	}

	public static void shutdown() {
		Iterator<ExecutorService> iterator = pools.iterator();
		while (iterator.hasNext()) {
			ExecutorService executorService = iterator.next();
			if (executorService != null) {
				executorService.shutdown();
			}
		}
	}
}
